package controllers

import (
	"fmt"
	"time"

	"github.com/pquerna/otp"
	"github.com/pquerna/otp/totp"

	"learn-otp/models"
)

type ApiController struct {
	BaseController
}

type apiResponse struct {
	RspCode RspCode
	RspInfo string
}

type RspCode string

const (
	SuccessCode RspCode = "00"
	ErrorCode   RspCode = "99"
)

func (c *ApiController) Validate() {
	accountName := c.GetString("account")
	appName := c.GetString("app")
	passCode := c.GetString("code")

	rsp := apiResponse{
		RspCode: ErrorCode,
	}

	if accountName == "" ||
		appName == "" ||
		passCode == "" {
		rsp.RspInfo = "invalid parameter"
		c.Data["json"] = rsp
		c.ServeJSON()
		return
	}

	user, err := userDao.GetUser2(accountName, appName)
	if err != nil {
		rsp.RspInfo = err.Error()
		c.Data["json"] = rsp
		c.ServeJSON()
		return
	}

	ok, err := totp.ValidateCustom(passCode, user.Secret, time.Now(), totp.ValidateOpts{
		Digits:    otp.DigitsSix,
		Algorithm: otp.AlgorithmSHA1,
		Skew:      1,
	})
	if err != nil {
		rsp.RspInfo = err.Error()
		c.Data["json"] = rsp
		c.ServeJSON()
		return
	}

	if ok {
		rsp.RspCode = SuccessCode
		rsp.RspInfo = "OTP校验通过"
	} else {
		rsp.RspInfo = "OTP校验不通过"
	}

	logDao.AddLog(&models.Log{
		AccountName: accountName,
		AppName:     appName,
		Passcode:    passCode,
		Result:      fmt.Sprint(ok),
	})

	c.Data["json"] = rsp
	c.ServeJSON()
}
